package com.cc.springboot_test.utils;

import com.cc.springboot_test.converter.ObjectConverter;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class BeanMapUtil {
    private static final Logger logger = LoggerFactory.getLogger(BeanMapUtil.class);

    // 对象转换为map
    public static <T> Map<String, Object> beanToMap(T obj) {
        if (obj == null) {
            return null;
        }

        try {
            Map<String, Object> map = Maps.newLinkedHashMap();
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String key = propertyDescriptor.getName();
                if (!StringUtils.equals(key, "class")) {
                    Method method = propertyDescriptor.getReadMethod();
                    Object invoke = method.invoke(obj);
                    map.put(key, invoke);
                }
            }
            return map;
        } catch (Exception e) {
            logger.error("JAVA对象转换为MAP错误，obj={}", ToStringBuilder.reflectionToString(obj, new NotNullStyle()), e);
            throw new RuntimeException(e);
        }
    }
}
